<?php
/**
 * Created by PhpStorm.
 * User: zhulei
 * Date: 2020/1/24
 * Time: 下午12:17
 * desc: 抽象Api基础类
 */

namespace App\HttpController\Api;

use App\HttpController\BaseController;
use EasySwoole\Http\Exception\ParamAnnotationValidateError;
use EasySwoole\EasySwoole\Core;
use EasySwoole\EasySwoole\Trigger;


abstract class ApiBase extends BaseController  {

    function index()
    {
        $this->actionNotFound('index');
    }

    protected function actionNotFound(?string $action): void
    {
        $this->writeJson(Status::CODE_NOT_FOUND,null,'接口不存在');
    }

    //请求截断可以做身份校验等
    function onRequest(?string $action): ?bool
    {
        if (!parent::onRequest($action)) {
            return false;
        };
        return true;
    }

    //异常抛出
    protected function onException(\Throwable $throwable): void
    {
        //validate 验证器
        if($throwable instanceof ParamAnnotationValidateError){
            $msg = $throwable->getValidate()->getError()->getErrorRuleMsg();
            $this->writeJson(400, null, "{$msg}");
        }else{
            if (Core::getInstance()->isDev()) {
                $this->writeJson(500, null, $throwable->getMessage());
            } else {
                Trigger::getInstance()->throwable($throwable);
                $this->writeJson(500, null, '系统内部错误，请稍后重试');
            }
        }
    }

}